/* eslint-disable prefer-promise-reject-errors */
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import router from '@/router'
import store from '../store/index'
import { getToken, removeToken } from '@/utils/auth'
let messageInstance = null

const resetMessage = (options) => {
    if (messageInstance) {
      messageInstance.close()
    }
    messageInstance = Message({
      message: '登录已过期',
      type: 'error',
      duration: 5 * 1000
    })
  },

  /* eslint-disable new-cap */
  service = new axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 40000
  })
service.interceptors.request.use(
  (config) => {
    // 是否需要设置 token
    const isToken = config.headers.isToken || false

    if (getToken() && !isToken) {
      // eslint-disable-next-line dot-notation
      config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?'
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName]
        var part = encodeURIComponent(propName) + '='
        if (value !== null && typeof value !== 'undefined') {
          if (typeof value === 'object') {
            for (const key of Object.keys(value)) {
              if (value[key] !== null && typeof value[key] !== 'undefined') {
                const params = propName + '[' + key + ']',
                  subPart = encodeURIComponent(params) + '='
                url += subPart + encodeURIComponent(value[key]) + '&'
              }
            }
          } else {
            url += part + encodeURIComponent(value) + '&'
          }
        }
      }
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    return config
  },
  (error) => {
    // console.log(error)
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (response.request.responseType != 'blob') {
      if (res.code == undefined || res.code === '') {
        // eslint-disable-next-line no-self-assign
        res.code = 1
      } else {
        // eslint-disable-next-line no-self-assign
        res.code = res.code
      }
      if (res.code != 1) {
        Message({
          message: '系统错误，请联系管理员！',
          type: 'error',
          duration: 3 * 1000
        })
      }
    }
    return res
  },
  (error) => {
    store.commit('updateLoading', false)
    // console.log(error) // for debug
    Message({
      message: error.message || error.msg,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
